import React from 'react'
import { useRef, useState } from 'react'
import { Col, Row, Button, Input, Table } from 'antd'
import axios from 'axios'
import '../user-manage/MusicList.css'
import imgStart from '../../../static/2.png';
import imgEnd from '../../../static/1.png';

export default function MusicList() {
  const inputText = useRef('')
  const [dataSource, setdataSource] = useState([])
  const [music, setmusic] = useState([])
  const [musiclist, setmusiclist] = useState([])
  const [currentMUsicLyric, setcurrentMUsicLyric] = useState([])
  const [lyricIndex, setlyricIndex] = useState(0)
  const [name, setname] = useState('')
  const [liststyle, setstyle] = useState(null)
  const [flag, setflag] = useState(null)
  const [num, setnum] = useState('')
  const [num1, setnum1] = useState('')
  const audio = document.querySelector('.audio');

  React.state = {
    lyricList: [],// 歌词数组
    currentTime: '',// audio当前播放时间
    currentLyc: 0, // 当前歌词
    lycStyle: {}// 歌词滚动样式
  }

  // const inputChange = (event) => {
  //   inputText = event.target.value
  // }

  // 获取相关歌曲
  const searchChange = () => {
    axios.get('https://autumnfish.cn/search?keywords=' + inputText.current.input.value).then(res => {
      setdataSource(res.data.result.songs)
    })
  }
  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
      align: 'center',
      render: (id) => {
        return <b>{id}</b>
      }
    },
    {
      title: '歌曲名称',
      dataIndex: 'name',
      key: 'name',
      align: 'center',
      render: (name) => {
        return <b>{name}</b>
      }
    },
    {
      title: '操作',
      align: "center",
      render(item, index) {
        if (item.id == num) {
          setflag(false)
          return <div>
            <Button type="primary" danger onClick={() => endPlay1()} >暂停</Button>
          </div>
        } else {
          setflag(true)
          return <div>
            <Button type="primary" onClick={() => confirmMethod(item, index)} >播放</Button>
          </div>
        }

      },
    },
  ];

  // 点击播放 通过歌曲id 获取播放链接
  const confirmMethod = (item, index) => {
    if (item.length == undefined) {
      audio.play();
      setnum(item.id)
      setnum1(item.id)
      setname(item.name)
      axios.get('https://autumnfish.cn/song/url?id=' + item.id).then(res => {
        setmusic(res.data.data[0].url)
      })

      axios.get('https://autumnfish.cn/lyric?id=' + item.id).then(res => {
        let result = res.data
        let lyricList = React.state.lyricList
        result['lrc']['lyric'].split(/[\n]/) // 截取中括号
          .forEach(item => {
            let temp = item.split(/\[(.+?)\]/)
            lyricList.push(
              {
                time: temp[1], // 时间
                lyc: temp[2] //歌词内容
              })
          })
        lyricList = lyricList.filter(v => v['lyc']) // 去除无歌词内容
        React.state.lyric = result['lrc']['lyric']
        setmusiclist(React.state.lyricList)

      })
    } else {
      item.forEach((el, index1) => {
        if (el.id == num1) {
          setnum(el.id)
          setname(el.name)
          audio.play();
          axios.get('https://autumnfish.cn/song/url?id=' + el.id).then(res => {
            setmusic(res.data.data[0].url)
          })

          axios.get('https://autumnfish.cn/lyric?id=' + el.id).then(res => {
            let result = res.data
            let lyricList = React.state.lyricList
            result['lrc']['lyric'].split(/[\n]/) // 截取中括号
              .forEach(el => {
                let temp = el.split(/\[(.+?)\]/)
                lyricList.push(
                  {
                    time: temp[1], // 时间
                    lyc: temp[2] //歌词内容
                  })
              })
            lyricList = lyricList.filter(v => v['lyc']) // 去除无歌词内容
            React.state.lyric = result['lrc']['lyric']
            setmusiclist(React.state.lyricList)

          })
        }
      })
    }

  }
  const format = (value) => { // 时间转换
    if (!value) return ''
    let interval = Math.floor(value)
    let minute = (Math.floor(interval / 60)).toString().padStart(2, '0')
    let second = (interval % 60).toString().padStart(2, '0')
    return `${minute}:${second}`
  }

  const timeUpdate = (e) => { // 播放位置发生时改变触发
    setflag(true)
    // 获取audio当前播放时间
    let currentTime = format(document.getElementsByTagName('audio')[0]['currentTime']); // 事件转换
    let { currentLyc } = React.state
    for (let i = currentLyc; i < musiclist.length; i++) {
      if (musiclist[i + 1] && currentTime < musiclist[i + 1]['time'] && currentTime > musiclist[i]['time']) {
        // console.log(musiclist[i + 1], currentTime, musiclist[i + 1]['time'], musiclist[i]['time'], 8888);
        setlyricIndex(i)
        setstyle({ transform: `translateY(-${53 * i}px)` })
      }
    }
  }

  const endPlay1 = () => {
    audio.pause();
    setnum(1)
    setflag(false)
  }





  return (
    <div>
      <div>
        <Row>
          <Col span={4}>
            <Input placeholder="请输入歌名" ref={inputText} type="text" />
          </Col>
          <Col span={3}>
            <Button style={{ marginLeft: '6px' }} type="primary" onClick={() => searchChange()}>查询</Button>
          </Col>
        </Row>
      </div>
      <div>
        <audio
          className='audio'
          style={{ display: 'none' }}
          autoPlay={true}
          controls={true}
          onTimeUpdate={(e) => timeUpdate(e)}
          src={music}></audio>
      </div>
      <div style={{ paddingTop: '12px', display: 'flex', justifyContent: 'space-between', boxSizing: 'border-box' }}>
        <div style={{ width: '48%' }}>
          <Table dataSource={dataSource} columns={columns} pagination={{
            pageSize: 10
          }} />
        </div>
        <div className='abc1' style={{ width: '35%', borderRadius: '12px', boxShadow: '0px 0px 10px 0px #ccc', paddingTop: '6%', boxSizing: 'border-box', }}>
          <div style={{ textAlign: 'center', fontSize: '24px', fontWeight: 'bold', marginBottom: '12px', color: '#fff' }}>{name}</div>
          <div className='lyric'>
            {
              musiclist.map((item, index) =>
                <div className='boxabc' style={liststyle}>
                  <p className='abc' key={index} style={lyricIndex === index ? { color: 'red', fontSize: '24px' } : {}}>{item.lyc}</p>
                </div>
              )
            }
          </div>
          <div style={{ width: '100px', height: '100px', margin: '0 auto', marginTop: '70px' }}>
            <img onClick={() => num != 1 ? endPlay1() : confirmMethod(dataSource)} style={{ width: '100%', height: '100%' }} src={num != 1 ? imgStart : imgEnd}></img>
          </div>
        </div>
      </div>
    </div>
  )
}
